package com.znsb.mxk.download;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import java.io.File;
import java.util.List;

/**
 * app版本更新处理
 * 
 * @author Win7
 *
 */
public class AppVersionUpdateHandler {
	private Context context;
	private UpdateAppBean updateAppBean;
	private UpdateServiceStatusListener updateServiceStatusListener;
	private DownloadProgressListener downloadProgressListener;
	private BroadCaseReceiveForUpdateStatusListener broadCaseReceiver;
	private UpdateAppBroadCastHandler updateAppBroadCaseHandler;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {// 通知开始更新
				updateAppBroadCaseHandler.sendUpdateContentBroadCaset(updateAppBean);
			}
		}
	};

	public AppVersionUpdateHandler(Context context) {
		super();
		this.context = context;
		broadCaseReceiver = new BroadCaseReceiveForUpdateStatusListener();
		updateAppBroadCaseHandler = new UpdateAppBroadCastHandler(context, broadCaseReceiver);
		updateAppBean = new UpdateAppBean();
	}

	/**
	 * 判断服务是否开启
	 * 
	 * @param mContext
	 * @return
	 */
	private boolean isServiceWork(Context mContext, Class<?> clasz) {
		String serviceName = clasz.getName();
		boolean isWork = false;
		ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> myList = myAM.getRunningServices(1024);
		if (myList.size() <= 0) {
			return false;
		}
		for (int i = 0; i < myList.size(); i++) {
			String mName = myList.get(i).service.getClassName().toString();
			if (mName.equals(serviceName)) {
				isWork = true;
				break;
			}
		}
		return isWork;
	}

	/**
	 * 获取apk文件保存的路径
	 * 
	 * @param versionCode
	 * @return
	 */
	private String getApkFilePath(int versionCode) {
		boolean sdCardUseable = false;
		try {
			sdCardUseable = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		if (sdCardUseable) {
			String directory = null;
			directory = Environment.getExternalStorageDirectory() + File.separator
					+ AppUpdateDownloadService.fileDectoryName + File.separator
					+ AppUpdateDownloadService.APP_BASE_NAME;

			String name = AppUpdateDownloadService.APP_BASE_NAME + versionCode + ".apk";

			return directory + File.separator + name;

		} else {
			return null;
		}
	}

	/**
	 * 更新服务状态监听回调
	 * 
	 * @author Win7
	 *
	 */
	public static interface UpdateServiceStatusListener {
		/**
		 * 接收到更新服务状态回调
		 * 
		 * @param serviceIsRunning
		 *            服务是否在运行
		 * @param isDownloading
		 *            更新是否正在下载
		 * @param isAutoRunning
		 *            是否是在后台静默下载更新（当设置了
		 *            下载后不自动安装、下载时在通知栏不提示进度、下载时不监听下载进度就认为属于静默下载）
		 */
		public void onReceiveUpdateServiceStatus(boolean serviceIsRunning, boolean isDownloading,
                                                 boolean isAutoRunning);
	}

	/**
	 * 下载进度监听
	 * 
	 * @author Win7
	 *
	 */
	public static interface DownloadProgressListener {
		/**
		 * 下载进度监听
		 * 
		 * @param currentProgress
		 * @param total
		 */
		public void onReviceProgressListener(long currentProgress, long total);
	}

	private class BroadCaseReceiveForUpdateStatusListener implements UpdateAppBroadCastHandler.OnReceiveUpdateListener {

		@Override
		public void onReceiveUpdateApp(UpdateAppBean updateBean) {

		}

		@Override
		public void onReceiveNetWorkChanged() {

		}

		@Override
		public void onReceiveRequestServiceStatus() {

		}

		@Override
		public void onReceiveServiceStatus(boolean isDownloading, boolean appFileIsExists, boolean isAutoRunning) {
			if (updateServiceStatusListener != null) {
				updateServiceStatusListener.onReceiveUpdateServiceStatus(true, isDownloading, isAutoRunning);
			}
		}

		@Override
		public void onReviceProgressChanged(long current, long total) {
			if (downloadProgressListener != null) {
				downloadProgressListener.onReviceProgressListener(current, total);
			}
		}

		@Override
		public void onReviceCancelUpdate() {

		}

		@Override
		public void onRevicePauseUpdate() {

		}

		@Override
		public void onReviceRestartUpdate() {

		}

	}

	/***************************** 外部调用接口 ***********************************/
	/****************************************************************/

	/**
	 * 开始更新（【在设置其它参数后调用】，【如果没有设置其它参数默认在wifi下才下载，下载成功后会自动安装，会在通知栏显示下载进度，不会监听下载进度】）
	 * 
	 * @param appUrl
	 */
	public final void startUpdate(String appUrl, int versionCode) {
		updateAppBean.setUrl(appUrl);
		updateAppBean.setVersionCode(versionCode);
		context.startService(new Intent(context, AppUpdateDownloadService.class));
		// 在启动service后延迟发送下载任务内容，直接在service启动后马上发送任务service还未初始化好，无法接受任务
		handler.sendEmptyMessageDelayed(1, 500);
	}

	/**
	 * 【在activity 销毁的时候调用此方法】
	 */
	public final void unRegisterUpdateService() {
		updateAppBroadCaseHandler.unRegisterReceiver();
	}

	/**
	 * 暂停下载
	 */
	public final void pause() {
		updateAppBroadCaseHandler.pauseUpdate();
	}

	/**
	 * 取消下载(取消下载后直接关闭了下载服务)
	 */
	public final void cancel() {
		updateAppBroadCaseHandler.cancelUpdate();
	}

	/**
	 * 暂停后继续下载
	 */
	public final void restart() {
		updateAppBroadCaseHandler.restartUpdate();
	}

	/**
	 * 设置只在wifi下更新(默认只在wifi下下载apk文件)
	 * 
	 * @param boo
	 */
	public final void setOnlyUpdateInWifi(boolean boo) {
		updateAppBean.setUpdateInWifi(boo);
	}

	/**
	 * 设置是否在通知栏里面显示下载进度【默认显示】
	 * 
	 * @param boo
	 */
	public final void setShowLoadingNitifiaction(boolean boo) {
		updateAppBean.setShowLoadingNotifiaction(boo);
	}
	
	/**
	 * 设置下载进度监听，用于在程序内部显示下载进度条【默认不获取更新进度,建议不使用此监听，会影响程序效率】
	 * 
	 * @param listener
	 */
	public final void setDownloadProgressListener(DownloadProgressListener listener) {
		this.downloadProgressListener = listener;
		updateAppBean.setSendDownloadProgress(true);
	}

	/**
	 * 设置当前版本apk在文件中已经存在或者在下载完成后是否在自动安装(默认会自动安装)
	 * 
	 * @param boo
	 */
	public final void setAutoInstallOnDownloaded(boolean boo) {
		updateAppBean.setAutoInstallOnDownloaded(boo);
	}


	/**
	 * 检查更新服务状态
	 * 
	 * @param listener
	 *            返回类容 ：1.服务是否在运行 2.是否正在下载更新
	 */
	public final void checkUpdateServiceStatus(UpdateServiceStatusListener listener) {
		this.updateServiceStatusListener = listener;
		boolean running = checkUpdateServiceIsRunning();
		if (running) {
			updateAppBroadCaseHandler.registerBroadCastReceiver(UpdateAppBroadCastHandler.UpdateAppConstant.SEND_SERVICE_STATUS_ACTION);
			updateAppBroadCaseHandler.sendBroadCastForRequestServiceState();
		} else if (!running && listener != null) {
			listener.onReceiveUpdateServiceStatus(false, false, false);
		}
	}

	/**
	 * 检查本地是否已经有该版本的apk安装包
	 * 
	 * @param
	 * @param
	 *
	 */
	public final boolean checkCurrentVersionApkFileIsExists(int versionCode) {
		String apkFilePath = getApkFilePath(versionCode);
		if (!TextUtils.isEmpty(apkFilePath)) {
			return new File(apkFilePath).exists();
		} else {
			return false;
		}
	}

	/**
	 * 如果本地已经下载好apk文件可以调用此方法安装apk文件
	 * 
	 * @param versionCode
	 * @param appType
	 */
	public final void installApk(int versionCode, int appType) {
		String apkFilePath = getApkFilePath(versionCode);
		boolean exists = false;
		if (!TextUtils.isEmpty(apkFilePath)) {
			exists = new File(apkFilePath).exists();
		} else {
			exists = false;
		}
		if (exists) {
			File file = new File(apkFilePath);
			if (file.exists()) {
				Intent intent = new Intent();
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
					intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					Uri contentUri = FileProvider.getUriForFile(context, "com.znsb.mxk.provider", file);
					intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
				} else {
					intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				}
//				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setAction(Intent.ACTION_VIEW);
//				intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
				context.startActivity(intent);
			}
		}
	}

	/**
	 * 检查下载服务是否正在运行
	 * 
	 * @return
	 */
	public final boolean checkUpdateServiceIsRunning() {
		return isServiceWork(context, AppUpdateDownloadService.class);
	}

	/**
	 * 判断当前网络是否是wifi
	 * 
	 * @return
	 */
	public final boolean isWifi() {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

}
